package src.Sixteen;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class MyClien extends JFrame {

    private PrintWriter writer;
    Socket socket;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    Container cc;

    public MyClien(String title){
        super(title);
        cc = this.getContentPane();
        cc.add(ta,"North");
        cc.add(tf,"South");
        tf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                writer.println(tf.getText());
                ta.append(tf.getText()+'\n');
                tf.setText(" ");
            }
        });
    }

    private void connect(){
        ta.append("尝试连接\n");
        try {
            InetAddress ip = InetAddress.getLocalHost();
            String hostAddress = ip.getHostAddress();
            System.out.println(hostAddress);
            socket = new Socket(hostAddress,8998);
            writer = new PrintWriter(socket.getOutputStream(),true);
            ta.append("完成连接\n");
            InetAddress netAddress = socket.getInetAddress();
            String netlp = netAddress.getHostAddress();
            int port = socket.getPort();
            InetAddress localAddress = socket.getLocalAddress();
            String hostAddress1 = localAddress.getHostAddress();
            int localPort = socket.getLocalPort();
            ta.append("远程服务器IP地址："+netlp+"\n");
            ta.append("远程服务器端口号："+port+"\n");
            ta.append("客户机本地的IP地址："+hostAddress1+"\n");
            ta.append("客户机本地的端口号："+localPort+"\n");
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null,"连接超时。。。");
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        MyClien clien = new MyClien("向服务器送数据");
        clien.setBounds(300,260,340,220);
        clien.setVisible(true);
        clien.connect();
    }
}
